package com.ftd.messagelistener.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ftd.messagelistener.activity.AlarmActivity;
import com.ftd.messagelistener.activity.MainActivity;
import com.ftd.messagelistener.R;
import com.ftd.messagelistener.base.Constants;
import com.ftd.messagelistener.bean.InterceptorBean;
import com.ftd.messagelistener.bean.SMSBean;
import com.ftd.messagelistener.data.AppDatabase;
import com.ftd.messagelistener.receiver.SMSReceiver;
import com.ftd.messagelistener.utils.AndroidScheduler;
import com.ftd.messagelistener.utils.DateUtil;
import com.ftd.messagelistener.utils.KeyWordUtils;
import com.ftd.messagelistener.utils.StringUtils;
import com.ftd.messagelistener.utils.WakeLockUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * tangxianfeng
 * 2021.11.28
 */
public class SMSService extends Service {

    private static final String TAG = "SMSService";
    public static final String ACTION = "com.ftd.messagelistener.startPlayService";

    private SMSReceiver smsReceiver;//监听广播
    private final MessageBinder messageBinder = new MessageBinder();
    private List<InterceptorBean> interceptorBeanlists =new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        if (smsReceiver == null) {
            smsReceiver = new SMSReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_SCREEN_ON);
            Log.e(TAG, "registerReceiver");
            //3.注册广播接收者
            registerReceiver(smsReceiver, filter);
        }//初始话广播
        if (interceptorBeanlists ==null|| interceptorBeanlists.size()==0){
            updateInterceptor();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand"+intent.getAction());

        String content="监听中....";
        String title="短信监听已开始";
        if (Constants.SMSAction.equals(intent.getAction())){
            String msg=intent.getStringExtra("msg");
            String phone=intent.getStringExtra("phone");
            SMSBean smsBean=compareSMS(phone,msg);
            if (smsBean!=null){
                if (msg.length()>6){
                    content=msg.substring(0,4)+"...";
                }else {
                    content=msg;
                }
                title="监听到"+phone;
                Log.e(TAG, smsBean.toString());

                Executors.newSingleThreadExecutor().execute(() -> AppDatabase.getInstance(SMSService.this).smsdao().insert(smsBean));
                WakeLockUtil.acquireWakeLock(getApplicationContext(),1000);
                Log.e(TAG, "GO TO SMS: "+smsBean.toString() );
                Intent alaemintent=new Intent(this, AlarmActivity.class);
                alaemintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                alaemintent.putExtra("SMSBean",smsBean);
                startActivity(alaemintent);
            }
        }//接收到消息内容的指令
        createNotifation(content,title);
        Log.e(TAG, "before start" + thread.getState().name());
        if (Constants.SMSUpdataAction.equals(intent.getAction())){
            updateInterceptor();

        }//接收到要更新词库的指令

        Log.e(TAG, "after start" + thread.getState().name());


        flags =getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.ECLAIR ? START_STICKY_COMPATIBILITY : START_STICKY;
        Log.e(TAG, "Notification Builder finished");
        return super.onStartCommand(intent, flags, startId);
    }

    //和拦截词库进行校验
    private SMSBean compareSMS(String phone,String msg){
        SMSBean smsBean=new SMSBean();
        for (InterceptorBean interceptorBean:interceptorBeanlists){
            if (!StringUtils.isEmpty(interceptorBean.getInterceptorcontent())&&msg.contains(interceptorBean.getInterceptorcontent())){
                Log.e(TAG, "interceptorBean.getInterceptorcontent()");
                smsBean.setMessage(KeyWordUtils.matcherSearchTitle(msg,interceptorBean.getInterceptorcontent()));
                smsBean.setDate(DateUtil.getStringDate());
                smsBean.setPhone(phone);
                return smsBean;
            }
            if (!StringUtils.isEmpty(interceptorBean.getInterceptorsend())&&phone.contains(interceptorBean.getInterceptorsend())){
                Log.e(TAG, "interceptorBean.getInterceptorsend()");
                smsBean.setMessage(msg);
                smsBean.setPhone(KeyWordUtils.matcherSearchTitle(phone,interceptorBean.getInterceptorcontent()));
                smsBean.setDate(DateUtil.getStringDate());
                return smsBean;
            }
        }
        return null;
    }

    //更新拦截词库
    private void updateInterceptor(){
        AppDatabase.getInstance(this)
                .interceptordao()
                .getAllByObservable()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<List<InterceptorBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull List<InterceptorBean> interceptorBeans) {
                        if (interceptorBeanlists!=null&&interceptorBeanlists.size()!=0&&interceptorBeanlists.size()!=interceptorBeans.size()){
                            Toast.makeText(SMSService.this,"拦截词库已更新",Toast.LENGTH_LONG).show();
                        }else if (interceptorBeanlists!=null&&interceptorBeanlists.size()!=0){
                            Toast.makeText(SMSService.this,"词库已为最新",Toast.LENGTH_LONG).show();
                        }else if (interceptorBeanlists!=null&&interceptorBeans.size()==0){
                            Toast.makeText(SMSService.this,"当前无拦截词",Toast.LENGTH_LONG).show();
                        }
                        interceptorBeanlists=interceptorBeans;

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind");
        return messageBinder;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "unregisterReceiver");
        unregisterReceiver(smsReceiver);
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        smsReceiver = null;
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }

    public class MessageBinder extends Binder {
        public SMSService getService() {
            return SMSService.this;
        }
    }


    private final Thread thread = new Thread(() -> {
        while (true){
            try {
                Log.e(TAG, "thread is starting");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });


    private void createNotifation(String content,String title){
        Notification.Builder builder = new Notification.Builder
                (this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class);
        builder.setContentIntent(PendingIntent.
                getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
                .setContentTitle(title) // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText(content) // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
        String CHANNEL_ONE_ID = "com.ftd.messagesms";
        String CHANNEL_ONE_NAME = "Channel SMS";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_MIN);
            notificationChannel.enableLights(false);
            notificationChannel.setShowBadge(false);//是否显示角标
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
            NotificationManager systemService = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            systemService.createNotificationChannel(notificationChannel);
            builder.setChannelId(CHANNEL_ONE_ID);
        }
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        //启动到前台
        startForeground(110, notification);
    }
}
